package com.etc.myblog.ser;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.apache.jasper.tagplugins.jstl.core.Out;

import com.etc.myblog.biz.ArticleBiz;
import com.etc.myblog.biz.PositionBiz;
import com.etc.myblog.biz.UserBiz;
import com.etc.myblog.entity.Position;
import com.etc.myblog.entity.User;
import com.etc.myblog.entity.UserArtCount;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.mysql.fabric.xmlrpc.base.Array;
import com.mysql.fabric.xmlrpc.base.Data;

public class UserSer extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取服务器中项目根目录
				String savePath =     
						  request.getServletContext().getRealPath("/resource/images/upload");
				java.io.File uploadDir = new java.io.File(savePath);
				//如果此目录不存在，新建该目录
		        if (!uploadDir.exists()) {
		            uploadDir.mkdir();
		        }
		UserBiz biz = new UserBiz();
		PositionBiz posBiz = new PositionBiz();
		ArticleBiz artBiz = new ArticleBiz();
		String tag = request.getParameter("tag");
		if (tag != null) {
			if (tag != "" && tag.equals("reg")) { //传送过来的tag值为注册，执行注册写入操作
				User user = new User();	//定义一个User,准备保存
				//新建一个SmartUpload,因form使用了enctype="multipart/form-data"
				//所以值变成二进制数据,request无法获取,故需要用此类获取值
				SmartUpload su = new SmartUpload();
				// 上传初始化
				su.initialize(this.getServletConfig(), request, response);//初始化su
				
				// 设定上传限制
				// 1.限制每个上传文件的最大长度。
				 su.setMaxFileSize(1024*1024*1024);		//限制为1M
				// 2.限制总上传数据的长度。
				 su.setTotalMaxFileSize(1024*1024*1024*2);	//限制为2M
				// 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。
				 su.setAllowedFilesList("jpg,jpeg,png,gif");
				// 4.设定禁止上传的文件（通过扩展名限制）,禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有
				//扩展名的文件。
				 try {
					su.setDeniedFilesList("exe,bat,jsp,htm,html");
				} catch (SQLException e1) {
					System.out.println(e1.getMessage());
					return;
				}
				try {	// 上传文件,采用UTF-8编码
					su.upload("utf-8");	
				} catch (SmartUploadException e) {
					System.out.println(e.getMessage());
					return;
				}
				if (!su.getFiles().getFile(0).isMissing()) {	//判断是否存在文件，如果文件存在
					int count = 0;
					try {
						count = su.save("/resource/images/upload");
						//获取刚上传的文件
						if (count == 0) {
							user.setUserImgUrl("/resource/images/upload/uuuser.jpg");
						} else {
							File file = su.getFiles().getFile(0);
							//获取文件名
							String imgName = file.getFileName();
							String serimgPath = "/resource/images/upload/";
							String imgPath = serimgPath + imgName;
							// 设置用户头像的图片路径
							user.setUserImgUrl(imgPath);
							System.out.println(count + "个文件上传成功！");
						}
					} catch (SmartUploadException e) {
						System.out.println(e.getMessage());
					}
				}
				
				String userName = su.getRequest().getParameter("userName");
				String userPwd = su.getRequest().getParameter("userPwd");
				String userEmail = su.getRequest().getParameter("userEmail");
				user.setUserName(userName);	//用户名
				user.setUserPwd(userPwd);	//密码
				user.setUserEmail(userEmail); //邮箱
				user.setUserBirthday(new Date());
				user.setUserRegTime(new Date());	//注册时间
				user.setUserDesc("用户简介");
				User user2 = biz.findUserByuserName(userName);
				if (user2 != null) {		//若是有相同用户名的,重新注册
					request.setAttribute("user", user);
					request.setAttribute("errMess", "该用户名已被注册");
					request.getRequestDispatcher("user/userRegister.jsp").forward(request, response);
					return;
				}
				request.getSession().setAttribute("user", user);
				biz.addUser(user);
				request.setAttribute("userCenter", user);
				request.getSession().setAttribute("user", user);
				request.getRequestDispatcher("user/userCenter.jsp").forward(request, response);
				/**
				 ****************\\\\原始获取+传值的方法////*********************
				 * User user = new User();
				user.setUserName(request.getParameter("userName"));	//用户名
				user.setUserPwd(request.getParameter("userPwd"));	//密码
				user.setUserEmail(request.getParameter("userEmail")); //邮箱
				Date date = new Date();
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String timeString = formatter.format(date);
				try {
					date = formatter.parse(timeString);
				} catch (ParseException e) {
					System.out.println(e.getMessage());
				}
				user.setUserRegTime(date);	//注册时间
				biz.addUser(user);
				System.out.println("注册成功");
				*************************************************************/
			} else if (tag != "" && tag.equals("login")) {
				try{// 传送过来的tag值为登录，读取数据库
				User user = biz.findUserByuserName(request.getParameter("username"));
				String pwd = request.getParameter("userpwd");
				if (pwd != null && user.getUserPwd().equals(pwd)) { // 密码匹配，登录成功
					if(user.getUserName().equals("root")) {
						request.setAttribute("userCenter", user);
						request.getSession().setAttribute("user", user);
						request.getRequestDispatcher("AdArticleSer").forward(request, response);
						return;
					}
					request.setAttribute("userCenter", user);
					request.getSession().setAttribute("user", user);
					request.getRequestDispatcher("user/userCenter.jsp").forward(request, response);
					//response.sendRedirect("user/userCenter.jsp");
					return;
				} else {
					// 登录失败
					request.setAttribute("errMess", "用户名或密码错误");
					request.getRequestDispatcher("user/userLogin.jsp").forward(request, response);
					//response.sendRedirect("user/userLogin.jsp");
					return;
				}
				}catch(Exception e){
					request.getRequestDispatcher("user/userLogin.jsp").forward(request, response);
				}
			} else if (tag != "" && tag.equals("modify")){
				User user = new User();	//定义一个User,准备保存
				int userId = Integer.parseInt(request.getParameter("userId"));
				user = biz.findById(userId);
				//新建一个SmartUpload,因form使用了enctype="multipart/form-data"
				//所以值变成二进制数据,request无法获取,故需要用此类获取值
				SmartUpload su = new SmartUpload();
				// 上传初始化
				su.initialize(this.getServletConfig(), request, response);//初始化su
				
				// 设定上传限制
				// 1.限制每个上传文件的最大长度。
				 su.setMaxFileSize(1024*1024*1024);		//限制为1M
				// 2.限制总上传数据的长度。
				 su.setTotalMaxFileSize(1024*1024*1024*2);	//限制为2M
				// 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。
				 su.setAllowedFilesList("jpg,jpeg,png,gif");
				// 4.设定禁止上传的文件（通过扩展名限制）,禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有
				//扩展名的文件。
				 try {
					su.setDeniedFilesList("exe,bat,jsp,htm,html");
				} catch (SQLException e1) {
					System.out.println(e1.getMessage());
					return;
				}
				try {	// 上传文件,采用UTF-8编码
					su.upload("utf-8");	
				} catch (SmartUploadException e) {
					System.out.println(e.getMessage());
					return;
				}
				
				//获取刚上传的文件
				File file = su.getFiles().getFile(0);
				//获取文件名
				String imgName = file.getFileName();
				
				if (!su.getFiles().getFile(0).isMissing()) {	//判断是否存在文件，如果文件存在
					int count = 0;
					try {
	
						System.out.println(imgName);
						count = su.save("/resource/images/upload");
						String serimgPath = "/resource/images/upload/";
						String imgPath = serimgPath + imgName;
							// 设置用户头像的图片路径
						user.setUserImgUrl(imgPath);
					} catch (SmartUploadException e) {
						System.out.println(e.getMessage());
					}
					System.out.println(count + "个文件上传成功！");
				}
				System.out.println(user.getUserImgUrl());
				Position position = new Position();
				int positionId = Integer.parseInt(su.getRequest().getParameter("positionId"));  //获取positionId
				position = posBiz.findPosByposId(positionId);     //获取职位对象
				
				user.setUserRealName(su.getRequest().getParameter("realname"));	//真实姓名
				user.setUserSex(su.getRequest().getParameter("usersex"));	//性别
				user.setUserPhone(su.getRequest().getParameter("phone"));   //电话
				user.setUserEmail(su.getRequest().getParameter("email")); //邮箱
				user.setUserAddress(su.getRequest().getParameter("address"));  //地址
				user.setPosition(position);   //设置职位对象
				
				
				Date birthday = new Date();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				try {
					birthday = format.parse(su.getRequest().getParameter("birthday"));
				} catch (ParseException e) {
					System.out.println(e.getMessage());
				}	
				user.setUserBirthday(birthday);//出生时间
				user.setUserDesc(su.getRequest().getParameter("desc"));
				user.setUserName((su.getRequest().getParameter("username_Read")));	//用户名
				if( imgName.equals("")) {
					biz.updateUserNopic(user);
				}
				
				biz.updateUser(user);
				
				//根据登录的用户获取信息，填充进用户中心
				User userCenter = new User();
				userCenter = (User) request.getSession().getAttribute("user");
				//获取带有外键关系的用户信息
				userCenter = biz.findById(userCenter.getUserId());
				request.setAttribute("userCenter", userCenter);
				request.getRequestDispatcher("user/userCenter.jsp").forward(request, response);
				return;
				
			} else if (tag != "" && tag.equals("pwdModify")) {
				String userName = request.getParameter("username_Read");
				String pwd = request.getParameter("userPwd");
				if (pwd.equals(biz.findUserByuserName(userName).getUserPwd())) {
					User user = new User();
					user.setUserName(userName);
					user.setUserPwd(request.getParameter("userNewPwd"));
					biz.updateUserPwd(user);
				} else {
					System.out.println("原密码不正确!");
					return;
				}
			}else if (tag != "" && tag.equals("logout")) {
				HttpSession session=request.getSession(false);  
		        if(session==null){  
		            response.sendRedirect("user/userLogin.jsp");  
		            return; 
		        }  
		        session.removeAttribute("user");  
		        response.sendRedirect("user/userLogin.jsp"); 
			}else if (tag != "" && tag.equals("center")) {
				//根据登录的用户获取信息，填充进用户中心
				User userCenter = new User();
				userCenter = (User) request.getSession().getAttribute("user");
				//获取带有外键关系的用户信息
				userCenter = biz.findById(userCenter.getUserId());
				request.setAttribute("userCenter", userCenter);
				request.getRequestDispatcher("user/userCenter.jsp").forward(request, response);
				return;
			}else if (tag != "" && tag.equals("toedit")) {
				User userCenter = new User();
				userCenter = (User) request.getSession().getAttribute("user");
				//获取带有外键关系的用户信息
				List<Position> posList = new ArrayList<Position>();
				posList = posBiz.find();
				userCenter = biz.findById(userCenter.getUserId());
				request.setAttribute("posList", posList);
				request.setAttribute("userEdit", userCenter);
				request.getRequestDispatcher("user/userPerInfoModify.jsp").forward(request, response);
				return;
			} else if (tag != "" && tag.equals("author")) {
				List<User> authorList = new ArrayList<>();
				authorList = biz.findAuthor();
				List<UserArtCount> userartCount = new ArrayList<>();
//				for (User user : authorList) {
//					System.out.println(artBiz.articleCount(user.getUserId()));
//					count[i] = artBiz.articleCount(user.getUserId());
//					i++;
//				}
				for(int i=0; i<authorList.size(); i++) {
					UserArtCount uacount = new UserArtCount();
					uacount.setUser(authorList.get(i));
					uacount.setArticleCount(artBiz.articleCount(authorList.get(i).getUserId()));
					uacount.setArticleView(artBiz.articleView(authorList.get(i).getUserId()));
					userartCount.add(uacount);
				}
				request.setAttribute("userartCount", userartCount);
				request.getRequestDispatcher("user/webAuthor.jsp").forward(request, response);
				return;
			}
		}
	
	}

}
